package com.nys.cqhttp.message.factory.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.nys.cqhttp.model.Massage;
import org.springframework.web.client.RestTemplate;

import com.nys.cqhttp.constant.CommonConstant;
import com.nys.cqhttp.message.factory.IMessageHandler;

import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * DirectImageUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 二次元
 * @date 2021/12/28 19:53
 */
@Slf4j
public class ErCiYuanMessageHandler implements IMessageHandler {

  private static final String TEMP_FILE = "/root/img";
  private static final String TEMP_FILE_PATH = "/root/img/temp_%s.jpg";

  @Override
  public List<String> listHandler(Massage messagePojo, Context context) {
    return Arrays.asList(handler(messagePojo, context));
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    RestTemplate restTemplate = SpringContextUtil.getBean("restTemplate");
    File file = new File(TEMP_FILE);
    File[] files = file.listFiles();
    for (File temp : files) {
      temp.delete();
    }
    FileOutputStream fos = null;
    try {
      byte[] bytes = restTemplate.getForEntity(messagePojo.getValue(), byte[].class).getBody();
      String tempFileName = String.format(TEMP_FILE_PATH, System.currentTimeMillis());
      fos = new FileOutputStream(new File(tempFileName));
      fos.write(bytes);
      fos.flush();
      return String.format(CommonConstant.CQ_IMAGE, "file:///" + tempFileName);
    } catch (Exception e) {
      log.error("e============>", e);
      return null;
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          log.error("关闭文件输出流失败...", e);
        }
      }
    }
  }
}
